import hashlib
from django.db import models
from db.base_model import BaseModel
from db.base_manager import BaseManager
from utils.get_hash import get_hash
from tinymce.models import HTMLField
# from django.contrib.auth.models import User


# Create your models here.

class AccountInfoManager(BaseManager):
    def add_account(self, username, password, email):
        obj = self.create_one_object(username=username, password=get_hash(password), email=email)
        return obj

    def handle_one_account(self, username, password=None):
        if password is None:
            obj = self.get_one_object(username=username)
        else:
            obj = self.get_one_object(username=username, password=get_hash(password))
        return obj


class AccountInfo(BaseModel):
    username = models.CharField(max_length=20, verbose_name='用户名')
    password = models.CharField(max_length=40, verbose_name='密码')
    email = models.EmailField(max_length=20, verbose_name='邮箱')
    objects = AccountInfoManager()

    class Meta:
        db_table = 'user_account'




class Tag(models.Model):
    name = models.CharField('标签', max_length=20, unique=True)

    class Meta:
        db_table = 'tag'
        verbose_name_plural = verbose_name = '标签'

    def __str__(self):
        return self.name

class BlogManager(BaseManager):
    def add_blog(self, title,  content, author):
        obj = self.create_one_object(title=title,  content=content, author_id=author)
        return obj

class Blog(BaseModel):
    id = models.AutoField(primary_key=True)
    author = models.ForeignKey(AccountInfo, on_delete=models.DO_NOTHING, verbose_name='作者')
    title = models.CharField('标题', max_length=50, null=False, blank=False)
    content = models.TextField('内容', null=False, blank=False)
    # content = HTMLField()
    created_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    tags = models.ManyToManyField(Tag, verbose_name='标签')
    views = models.PositiveIntegerField(default=0)

    objects = BlogManager()

    class Meta:
        db_table = 'blog'
        verbose_name_plural = verbose_name = '文章'
        ordering = ['-created_time']

    def count_views(self):
        self.views += 1
        self.save(update_fields=['views'])

    def get_absolute_url(self):
        return "/blog/" + str(self.id)

    def pre_blog(self):
        return Blog.objects.filter(id__lt=self.id).first()

    def next_blog(self):
        return Blog.objects.filter(id__gt=self.id).first()

    def __str__(self):
        return self.title


# class BlogTagLink(models.Model):
#     """
#     博客标签关联表
#     """
#     # __tablename__ = "blog_tag_link"
#
#     blog_id = models.ForeignKey(Blog, on_delete=models.DO_NOTHING, verbose_name='博客')
#     tag_id = models.ForeignKey(Tag, on_delete=models.DO_NOTHING, verbose_name='标签')
#
#
#     class Meta:
#         db_table = 'blog_tag_link'